package cn.iocoder.yudao.module.erp.service.dispatchvehicle;

import cn.iocoder.yudao.module.erp.controller.admin.common.LocalDateAdapter;
import cn.iocoder.yudao.module.erp.controller.admin.common.LocalDateTimeAdapter;
import cn.iocoder.yudao.module.erp.dal.dataobject.dp.DpAlmtDO;
import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import cn.iocoder.yudao.module.erp.controller.admin.dispatchvehicle.vo.*;
import cn.iocoder.yudao.module.erp.dal.dataobject.dispatchvehicle.DispatchVehicleDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.erp.dal.mysql.dispatchvehicle.DispatchVehicleMapper;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.erp.enums.ErrorCodeConstants.*;

/**
 * 总配车信息 Service 实现类
 * @author 天使管理员
 */
@Service
@Validated
public class DispatchVehicleServiceImpl implements DispatchVehicleService {

    @Resource
    private DispatchVehicleMapper dispatchVehicleMapper;

    @Override
    public Long createDispatchVehicle(DispatchVehicleSaveReqVO createReqVO) {
        // 插入
        DispatchVehicleDO dispatchVehicle = BeanUtils.toBean(createReqVO, DispatchVehicleDO.class);
        dispatchVehicleMapper.insert(dispatchVehicle);
        // 返回
        return dispatchVehicle.getId();
    }

    @Override
    public void updateDispatchVehicle(DispatchVehicleSaveReqVO updateReqVO) {
        // 校验存在
        validateDispatchVehicleExists(updateReqVO.getId());
        // 更新
        DispatchVehicleDO updateObj = BeanUtils.toBean(updateReqVO, DispatchVehicleDO.class);
        dispatchVehicleMapper.updateById(updateObj);
    }

    @Override
    public List<DispatchVehicleDO> dispatchVehicleList(Integer line,String dpId) {
        return dispatchVehicleMapper.selectByDispatch(null, line,null, null, dpId );
    }

    @Override
    public void deleteDispatchVehicle(Long id) {
        // 校验存在
        validateDispatchVehicleExists(id);
        // 删除
        dispatchVehicleMapper.deleteById(id);
    }

    private void validateDispatchVehicleExists(Long id) {
        if (dispatchVehicleMapper.selectById(id) == null) {
            throw exception(DISPATCH_VEHICLE_NOT_EXISTS);
        }
    }

    @Override
    public DispatchVehicleDO getDispatchVehicle(Long id) {
        return dispatchVehicleMapper.selectById(id);
    }

    @Override
    public PageResult<DispatchVehicleDO> getDispatchVehiclePage(DispatchVehiclePageReqVO pageReqVO) {
        return dispatchVehicleMapper.selectPage(pageReqVO);
    }

    @Override
    public PageResult<DispatchVehicleDO> getDispatchVehicleOuterPage(DispatchVehiclePageReqVO pageReqVO) {
        //条件为出库
        pageReqVO.setInventoryStatus(1);
        return dispatchVehicleMapper.selectOutPage(pageReqVO);
    }

    @Override
    public PageResult<DispatchVehicleDO> getTransportPage(DispatchVehiclePageReqVO pageReqVO) {
        String dispatchNumber = pageReqVO.getDispatchNumber();
        Integer origin = pageReqVO.getOrigin();
        Integer dest = pageReqVO.getDest();
        String driverPhone = pageReqVO.getDriverPhone();
        String dpId = pageReqVO.getDpId();
        Integer pageNo = pageReqVO.getPageNo();
        Integer pageSize = pageReqVO.getPageSize();
        // 计算起始行
        int offset = (pageNo - 1) * pageSize;
        // 调用查询方法
        List<DispatchVehicleDO> dispatchVehicles = dispatchVehicleMapper.getTransportPage(dpId, dispatchNumber, origin, dest, driverPhone, offset, pageSize);
        // 查询总数
        Long totalCount = dispatchVehicleMapper.getTransportPageCount(dpId, dispatchNumber, origin, dest, driverPhone);
        // 返回分页结果
        return new PageResult(dispatchVehicles, totalCount);
    }

    @Override
    public void lineDetailsUpdate(List<DispatchVehicleSaveReqVO> createReqVO) {
        List<DispatchVehicleDO> list = BeanUtils.toBean(createReqVO, DispatchVehicleDO.class);
        List<DispatchVehicleDO> updateList = new ArrayList<DispatchVehicleDO>();
        for (DispatchVehicleDO vehicle : list) {
            String incomingAddress = vehicle.getAddress();
            //前端传入的lineDetails为空则执行下一个循环
            if (incomingAddress == null || StringUtils.isBlank(incomingAddress)) {
                continue;
            }
            List<DispatchVehicleDO> vehicleList = dispatchVehicleMapper.selectByDispatchNumber(vehicle.getDispatchNumber());
            for (DispatchVehicleDO dispatch : vehicleList) {
                // 获取数据库中的lineDetails
                String existingLineDetails = dispatch.getLineDetails();
                if (existingLineDetails != null && StringUtils.isNotBlank(existingLineDetails)) {
                    dispatch.setLineDetails(existingLineDetails + "," + incomingAddress);
                } else {
                    dispatch.setLineDetails(incomingAddress);
                }

                // 获取当前时间并格式化
                String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                //处理时间
                String addressCreateTimes = dispatch.getAddressCreateTimes();
                if (addressCreateTimes != null && StringUtils.isNotBlank(addressCreateTimes)) {
                    dispatch.setAddressCreateTimes(addressCreateTimes + "," + currentTime);
                } else {
                    dispatch.setAddressCreateTimes(currentTime);
                }
                updateList.add(dispatch);
            }
        }
        dispatchVehicleMapper.updateById(updateList);
    }

    public void updateDpData(String id, Integer inCount, Integer signNum, Integer inPutNum) {
        // 查询签收总数
//        Integer sumSignNum = dpSignMapper.getSumSignNum(id);
//        if (sumSignNum == null){
//            sumSignNum = 0;
//        }
        //JSON 反序列化
        Gson gson = new GsonBuilder()
                .registerTypeAdapter(LocalDate.class, new LocalDateAdapter())
                .registerTypeAdapter(LocalDateTime.class, new LocalDateTimeAdapter())
                .create();
        signNum = signNum + inPutNum;
        // 查询 dispatch_vehicle 表中对应的数据
        List<DispatchVehicleDO> disp = dispatchVehicleMapper.selectList(
                new QueryWrapper<DispatchVehicleDO>()
                        .eq("dp_id", id)
                        .eq("inventory_status", 1));
        if (disp.size() == 1) {
            if (signNum >= inCount) {
                dispatchVehicleMapper.deleteDispById(id, 1);
            } else {
                DispatchVehicleDO dispDO = disp.get(0);
                DpAlmtDO dpAlmtDO = gson.fromJson(dispDO.getDpData(), DpAlmtDO.class);
                Integer oldOutCount = dpAlmtDO.getOutCount();
                dpAlmtDO.setOutCount(oldOutCount - inPutNum);
                // 重新序列化为 JSON, 更新回数据库
                String newDpData = gson.toJson(dpAlmtDO);
                DispatchVehicleDO updateObj = new DispatchVehicleDO();
                updateObj.setId(dispDO.getId());
                updateObj.setDpData(newDpData);
                dispatchVehicleMapper.updateById(updateObj);
            }
        } else {
            List<Long> ids = new ArrayList<>();
            Integer subCount = null; // 记录前一次相减后的件数
            for (DispatchVehicleDO vehicleDO : disp) {
                DpAlmtDO dpAlmtDO = gson.fromJson(vehicleDO.getDpData(), DpAlmtDO.class);
                Integer oldOutCount = dpAlmtDO.getOutCount();
                if (subCount == null) {   // 如果是第一次循环
                    subCount = oldOutCount - inPutNum;
                } else {            // 后续循环
                    subCount = oldOutCount - Math.abs(subCount);
                }
                if (subCount >= 0) {
                    dpAlmtDO.setOutCount(subCount);
                    // 重新序列化为 JSON,更新回数据库
                    String newDpData = gson.toJson(dpAlmtDO);
                    DispatchVehicleDO updateObj = new DispatchVehicleDO();
                    updateObj.setId(vehicleDO.getId());
                    updateObj.setDpData(newDpData);
                    dispatchVehicleMapper.updateById(updateObj);
                } else {
                    ids.add(vehicleDO.getId());
                }
            }
            // 循环结束后批量删除
            if (!ids.isEmpty()) {
                dispatchVehicleMapper.deleteBatchIds(ids);
            }
        }
    }

}